package com.xcm.sso.client.util;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * Base64工具类
 */
public class Base64Utils {
	/**
	 * 编码
	 * @param str   需要被编码的字符串
	 * @param charset   字符编码
	 * @return  返回编码后的字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String encode(String str, String charset) throws UnsupportedEncodingException {
		if (StringUtils.isBlank(charset)) {
			throw new NullPointerException("编码不能为空");
		}
		final Base64.Encoder encoder = Base64.getEncoder();
		final byte[] bytes = str.getBytes(charset);
		return encoder.encodeToString(bytes);
	}

	/**
	 * 解码
	 * @param str   需要被解码的字符串
	 * @return  被解码后的字符串
	 * @throws UnsupportedEncodingException
	 */
	public static String decode(String str) {
		final Base64.Decoder decoder = Base64.getDecoder();
		final byte[] decode = decoder.decode(str);
		return new String(decode);
	}
}
